﻿<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/9/25
 * Time: 10:28
 */
class LotteryAction extends Action{
    public function getLottery(){
        $url = 'http://f.apiplus.cn/cqssc-2.json';
        $result = self::httpGet($url);

        Session::switchCustomer(0);
        $lotteryModule = M("module_mill_lottery");
        $periodModule = M("module_mill_period");
        $numberModule = M("module_mill_number");
        $parModule = M("module_mill_par");
        $LotteryList = json_decode($result, true);
        foreach($LotteryList['data'] as $key=>$value){
            $data['lotteryPerId'] = $value['expect'];
            $data['lottery'] = '重庆时时彩';
            $data['lotteryNumber'] = $value['opencode'];
            $data['lotteryTime'] = $value['opentime'];
            $data['createTime'] = date('Y-m-d H:i:s',time());
            $condition['lotteryPerId'] = array("eq",$value['expect']);
            $arr = $lotteryModule->where($condition)->find();
            if(!$arr){
                $lotteryId = $lotteryModule->add($data);
                $opentime = $value['opentime'];
                $periodList = $periodModule->where("periodState=2 and updataTime < '".$opentime."'")->select();
                foreach($periodList as $k=>$period){
                    $cid = $period["fromCustomerId"];
                    Session::switchCustomer($cid);
                    $TemplateModel = M("template_messages");
                    $periodId = $period['id'];
                    $arr = $periodModule->alias("a")
                        ->join("inner join wx_module_product b on a.pid = b.id")
                        ->where("a.id = $periodId")
                        ->field("a.timeTogether,b.totalCopies,b.name")
                        ->find();
                    $pid = $period["pid"];
                    $timeTogether = $arr["timeTogether"];
                    $totalCopies = $arr["totalCopies"];
                    $str = str_replace(",","",$value['opencode']);
                    $wNumber = ($timeTogether+$str)%$totalCopies+100001;
                    $periodData['lotteryId'] = $lotteryId;
                    $periodData['periodState'] = 3;
                    $periodData['updataTime'] = date('Y-m-d H:i:s',time());
                    $periodData['wNumber']=$wNumber;
                    $periodData["lotteryId"] = $lotteryId;
                    $periodModule->where("id=$periodId")->save($periodData);
                    $where["a.number"] = $wNumber;
                    $where["a.perId"] = $periodId;
                    $winner = $numberModule->alias("a")
                        ->join("inner join wx_module_mill_par b on a.parId = b.id")
                        ->where($where)->field("a.id,a.openId,a.parId,b.fromOpenId as recOpenId,b.oid")->find();
                    $param = new stdClass();
                    $param->id = $winner["oid"];
                    $param->userName = $winner["openId"];
                    Module::callModule("product",NULL,"SendVirtualCode",$param);
                    $numberModule->alias("a")->where($where)->setField("nState",1);
                    $parData["parState"]=2;
                    $parData["updateTime"] = date("Y-m-d H:i:s");
                    $parModule->where("id=".$winner["parId"])->save($parData);
                    $parData["parState"]=3;
                    $parModule->where("openId='".$winner["recOpenId"]."' and perId = ".$periodId)->save($parData);
                    //发送模板消息
                    $twhere['status'] = "indianaWinning";
                    $templatemsg = $TemplateModel->where($twhere)->find();
                    $templateId = $templatemsg['templateId'];
                    $data['first'] = array('value'=> '喂！你参加的夺宝大富翁中奖啦！','color'=>"#743A3A");
                    $data['keyword1'] = array('value'=> '夺宝大富翁','color'=>'#173177');
                    $data['keyword2'] = array('value'=> $arr["name"],'color'=>'#173177');
                    $data['remark'] = array('value'=> '点击查看奖品',"color"=>'#008000');
                    $toUser = $winner["openId"];
                    $template_id = $templateId;
                    $url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
                        "&module=product&method=getProduct&params=%7B%22id%22%3A%22$pid%22,%22periodId%22%3A$periodId%7D";
                    $url = urlencode($url);
                    $topcolor = "#FF0000";
                    //data得转json
                    WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
                    if($winner["recOpenId"]){
                        $data['keyword2'] = array('value'=> '推荐奖','color'=>'#173177');
                        $toUser = $winner["recOpenId"];
                        //data得转json
                        WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
                    }
//                    $parList = $parModule->alias("a")
//                        ->join("left join wx_".$cid."_user_weixin_info b on a.openId = b.openid")
//                        ->where("parState = 1 and perId = ".$periodId." and a.openId <> '".$winner["openId"]."' and a.openId <> '". $winner["recOpenId"]."'")
//                        ->field("a.openId,b.nickname")->select();
//                    foreach($parList as $key => $par){
//                        //图文消息   加链接
//                        $articles=array();
//                        $article=new stdClass();
//                        $article->title=urlencode("夺宝中奖揭晓提示");
//                        $url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
//                            "&module=product&method=getProduct&params=%7B%22id%22%3A%22$pid%22%2C%22periodId%22%3A%22$periodId%22%7D";
//                        $text="中奖结果通知\n亲爱的".$par["nickname"]."\n夺宝大富翁开奖啦！\n夺宝奖品：".$arr["name"]."\n开奖结果：未中奖\n运气还差一点点，再试试手气吧，说不定下一个抽中的就是你喔！";
//                        $article->description=urlencode($text);
//                        $url = urlencode($url);
//                        $article->url=$url;
//                        $article->picurl="";
//                        array_push($articles, $article);
//                        $toUser = $par["openId"];
//                        WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
//                    }
                    //更改订单状态
                    $parList = $parModule->alias("a")
                        ->join("inner join wx_module_product_order b on a.oid = b.id")
                        ->where("a.perId=$periodId and a.parState <> 2 and a.parState <> 3 and b.status='partake'")->select();
                    foreach($parList as $key=>$par){
                        $oid = $par["oid"];
                        R('Product/myqupdateDividents',array($oid));
                    }
                }
            }
        }
    }
    public static function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}